var layer = layui.layer,
    laytpl = layui.laytpl;

$(function () {
    // Waves初始化
    Waves.displayEffect();
    // 数据表格动态高度
    $(window).resize(function () {
        $('#table').bootstrapTable('resetView', {
            height: getHeight()
        });
    });
    if ($("#iframe_aside").length > 0) {
        $("#main").css("width", "80%");
    }
});
// 动态高度
function getHeight() {
    return $(window).height() - 20;
}
function timeFormatter(value, row, index) {
    if (value) {
        return new Date(value).toLocaleString();
    }
    return "";
}
function dateFormatter(value, row, index) {
    if (value) {
        return new Date(value).toLocaleDateString();
    }
    return "";
}
function monthFormatter(value, row, index) {
    if (value) {
        var date = new Date(value);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        return year + "年" + month + "月";
    }
    return "";
}
// 数据表格展开内容
function detailFormatter(index, row) {
    /*var html = [];
     $.each(row, function (key, value) {
     html.push('<p><b>' + key + ':</b> ' + value + '</p>');
     });
     return html.join('');*/
    return false;
}


function getPageHtml(data) {
    var tpl = $("#page_tag").html();
    var pageHtml = "";
    laytpl(tpl).render(data, function (html) {
        pageHtml = html
    });
    return pageHtml;
}
function getDeleteHtml(data) {
    var tpl = $("#delete_tag").html();
    var deleteHtml = "";
    laytpl(tpl).render(data, function (html) {
        deleteHtml = html
    });
    return deleteHtml;
}

var Common = {
    layer: null,
    laytpl: null,
    openPage: function (param) {
        var defaultParam = {
            title: "",//page标题
            url: "",
            param: "",//参数
            isFull: false,//是否全屏
            isMaxMin: false,//是否支持最大最小化
            width: "680px",//初始宽度
            length: "80%"//初始高度
        };
        //合并参数，替换前者中相同的参数
        $.extend(defaultParam, param);
        var url = defaultParam.url + defaultParam.param;
        var pageIndex = layer.open({
            type: 2,
            title: defaultParam.title,
            shadeClose: true,
            shade: 0.8,
            area: [defaultParam.width, defaultParam.length],
            content: url,
            maxmin: defaultParam.isMaxMin
        });
        if (defaultParam.isFull) {
            layer.full(pageIndex);
        }
    },
    toolBarUpdate: function (param) {
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length != 1) {
            layer.msg("请选择一条记录！");
        } else {
            var id = rows[0][param.id];
            param.url = param.url + id;
            Common.openPage(param);
        }
    },
    /**
     * 将json格式的参数拆解为url格式
     * @param paramJson json格式的参数
     * @returns {string} ？ + 参数 + & + 参数 的格式
     */
    getParam: function (paramJson) {
        var param = '';
        if (paramJson) {
            param += '?';
            var i = 0;
            //手动拼接参数
            for (var key in paramJson) {
                if (i > 0) {
                    param += '&';
                }
                param += key + '=' + paramJson[key];
                i++;
            }
        }
        return param;
    },
    /**
     * 批量删除
     * @param url
     * @param afterDelete
     */
    batchDelete: function (param) {
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length == 0) {
            layer.msg('请至少选择一条记录！', {icon: 5});
        } else {
            layer.confirm('确定删除么？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var defaultParam = {
                    url: "",
                    id: "id",
                    afterDelete: function () {

                    }
                };
                //合并参数，替换前者中相同的参数
                $.extend(defaultParam, param);

                //拼接URL地址
                var url = defaultParam.url;
                var ids = new Array();
                for (var i in rows) {
                    ids.push(rows[i][defaultParam.id]);
                }
                if (url.charAt(url.length - 1) == "/") {
                    url = url + ids.join("-");
                } else {
                    url = url + "/" + ids.join("-");
                }
                $.ajax({
                    type: 'get',
                    url: url,
                    success: function (res) {
                        if (res.code != 1) {
                            if (typeof(res.data) != "undefined" && res.data.length > 0) {
                                layer.msg(res.data, {icon: 5});
                            } else {
                                layer.msg(res.message, {icon: 5});
                            }
                        } else {
                            layer.msg('删除成功！', {icon: 1});
                            $table.bootstrapTable('refresh');
                            if (typeof (defaultParam.afterDelete) == "function") {
                                defaultParam.afterDelete();
                            }
                        }
                    },
                    error: function (res) {
                        layer.msg('删除失败！', {icon: 5});
                    }
                });
            }, function () {
            });
        }
    },
    /**
     * 单个删除
     * @param url
     * @param id
     * @param afterDelete
     */
    deleteOne: function (url, id, afterDelete) {
        layer.confirm('确定删除么？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            $.ajax({
                type: 'GET',
                url: url + "/" + id,
                success: function (res) {
                    if (res.code != 1) {
                        if (typeof(res.data) != "undefined" && res.data.length > 0) {
                            layer.msg(res.data, {icon: 5});
                        } else {
                            layer.msg(res.message, {icon: 5});
                        }
                    } else {
                        layer.msg('删除成功！', {icon: 1});
                        $table.bootstrapTable('refresh');
                        if (typeof (afterDelete) == "function") {
                            afterDelete();
                        }
                    }
                },
                error: function (res) {
                    layer.msg('删除失败！', {icon: 5});
                }
            });
        }, function () {
        });
    },

    //表格tr下移
    trDown: function () {
        var trs = $(".selected");
        var next;
        for (var i = trs.length - 1; i >= 0; i--) {
            var tr = $(trs[i]);
            next = tr.next();
            if (next.length < 1) {
                continue;
            }
            if (next.hasClass("selected")) {
                continue;
            }
            next.after(tr);
        }
    },
    //表格tr上移
    trUp: function () {
        var trs = $(".selected");
        var prev;
        for (var i = 0; i < trs.length; i++) {
            var tr = $(trs[i]);
            prev = tr.prev();
            if (prev.length < 1) {
                continue;
            }
            if (prev.hasClass("selected")) {
                continue;
            }
            prev.before(tr);
        }
    },
    //保存排序
    saveSort: function (url) {
        var sortData = Common.sortTable();
        $.ajax({
            url: url,
            data: JSON.stringify(sortData),
            type: "post",
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                if (res.code != 1) {
                    if (res.data.length > 0) {
                        layer.msg(res.data, {icon: 5});
                    } else {
                        layer.msg(res.message, {icon: 5});
                    }
                } else {
                    layer.msg('保存成功！', {icon: 1});
                    $table.bootstrapTable('refresh');
                }
            },
            error: function (res) {
                layer.msg('保存失败！', {icon: 5});
            }
        })
    },
    //获取表格当前排序数据
    sortTable: function () {
        var trs = $("tbody").find("tr");
        var sortData = [];
        for (var i = 0; i < trs.length - 1; i++) {
            var id = $(trs[i]).find(".hiddenDiv").html();
            var sort = $($(trs[i]).find("td")[3]).html();
            sortData.push({id: id, sort: sort})
        }
        return sortData;
    }
};

